package com.utooo.service.supplier;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.utooo.dao.purchase.ContractAgreementsStageMapper;
import com.utooo.dao.purchase.ContractAttachmentMapper;
import com.utooo.dao.purchase.ContractObjectMapper;
import com.utooo.dao.purchase.ContractPartyAMapper;
import com.utooo.dao.purchase.ContractPartyBMapper;
import com.utooo.dao.purchase.PurchaseContractMapper;
import com.utooo.dao.purchase.ThirdPartyMapper;
import com.utooo.dao.supplier.SupplierContractMapper;
import com.utooo.pojo.domain.purchase.contract.ContractAgreementsStageDO;
import com.utooo.pojo.domain.purchase.contract.ContractAttachmentDO;
import com.utooo.pojo.domain.purchase.contract.ContractObjectDO;
import com.utooo.pojo.domain.purchase.contract.ContractPartyADO;
import com.utooo.pojo.domain.purchase.contract.ContractPartyBDO;
import com.utooo.pojo.domain.purchase.contract.PurchaseContractDO;
import com.utooo.pojo.domain.purchase.contract.ThirdPartyDO;
import com.utooo.pojo.domain.supplier.SupplierContactDO;
import com.utooo.pojo.dto.common.RestResult;
import com.utooo.service.purchase.PurchaseContractService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.utooo.constant.Constans.IGNORED_PROPERTIES;

@Service
public class SupplierContractServiceImpl extends ServiceImpl<SupplierContractMapper, SupplierContactDO>
        implements SupplierContractService {

    @Resource
    private ContractPartyAMapper contractPartyAMapper;
    @Resource
    private ContractPartyBMapper contractPartyBMapper;
    @Resource
    private ThirdPartyMapper thirdPartyMapper;
    @Resource
    private ContractObjectMapper contractObjectMapper;
    @Resource
    private ContractAgreementsStageMapper contractAgreementsStageMapper;
    @Resource
    private ContractAttachmentMapper contractAttachmentMapper;
    @Resource
    private PurchaseContractMapper purchaseContractMapper;
    @Resource
    private PurchaseContractService purchaseContractService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addContract(String contractId) {
        SupplierContactDO supplierContact = this.getById(contractId);
        if (supplierContact == null) {
            throw new RuntimeException("合同不存在");
        }
        PurchaseContractDO purchaseContract = new PurchaseContractDO();
        BeanUtil.copyProperties(supplierContact, purchaseContract, IGNORED_PROPERTIES);
        purchaseContractMapper.insert(purchaseContract);
        String id = purchaseContract.getId();

        CopyOptions copyOptions = CopyOptions.create().setIgnoreProperties(IGNORED_PROPERTIES);
        // 甲方
        List<ContractPartyADO> contractPartyAs = contractPartyAMapper
                .selectList(new LambdaQueryWrapper<ContractPartyADO>()
                        .eq(ContractPartyADO::getForeignId, contractId));
        List<ContractPartyADO> supplierContractPartyAs = BeanUtil.copyToList(contractPartyAs, ContractPartyADO.class, copyOptions);
        supplierContractPartyAs.forEach(i -> i.setForeignId(id));
        contractPartyAMapper.insert(supplierContractPartyAs);

        // 乙方
        List<ContractPartyBDO> contractPartyBs = contractPartyBMapper
                .selectList(new LambdaQueryWrapper<ContractPartyBDO>()
                        .eq(ContractPartyBDO::getForeignId, contractId));
        List<ContractPartyBDO> supplierContractPartyBs = BeanUtil.copyToList(contractPartyBs, ContractPartyBDO.class, copyOptions);
        supplierContractPartyBs.forEach(i -> i.setForeignId(id));
        contractPartyBMapper.insert(supplierContractPartyBs);

        // 第三方
        List<ThirdPartyDO> thirdParties = thirdPartyMapper
                .selectList(new LambdaQueryWrapper<ThirdPartyDO>()
                        .eq(ThirdPartyDO::getForeignId, contractId));
        List<ThirdPartyDO> supplierThirdParties = BeanUtil.copyToList(thirdParties, ThirdPartyDO.class, copyOptions);
        supplierThirdParties.forEach(i -> i.setForeignId(id));
        thirdPartyMapper.insert(supplierThirdParties);

        // 合同标的
        List<ContractObjectDO> contractObjects = contractObjectMapper
                .selectList(new LambdaQueryWrapper<ContractObjectDO>()
                        .eq(ContractObjectDO::getForeignId, contractId));
        List<ContractObjectDO> supplierContractObjects = BeanUtil.copyToList(contractObjects, ContractObjectDO.class, copyOptions);
        supplierContractObjects.forEach(i -> i.setForeignId(id));
        contractObjectMapper.insert(supplierContractObjects);

        // 合同约定阶段
        List<ContractAgreementsStageDO> agreementsStages = contractAgreementsStageMapper
                .selectList(new LambdaQueryWrapper<ContractAgreementsStageDO>()
                        .eq(ContractAgreementsStageDO::getForeignId, contractId));
        List<ContractAgreementsStageDO> supplierAgreementsStages =
                BeanUtil.copyToList(agreementsStages, ContractAgreementsStageDO.class, copyOptions);
        supplierAgreementsStages.forEach(i -> i.setForeignId(id));
        contractAgreementsStageMapper.insert(supplierAgreementsStages);

        // 合同信息
        List<ContractAttachmentDO> contractAttachments = contractAttachmentMapper
                .selectList(new LambdaQueryWrapper<ContractAttachmentDO>()
                        .eq(ContractAttachmentDO::getForeignId, contractId));
        List<ContractAttachmentDO> supplierContractAttachments =
                BeanUtil.copyToList(contractAttachments, ContractAttachmentDO.class, copyOptions);
        supplierContractAttachments.forEach(i -> i.setForeignId(id));
        contractAttachmentMapper.insert(supplierContractAttachments);
    }

    @Override
    public String generateContractNo() {
        String contractNoPrefix = "AG";

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        String datePart = currentDate.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        // 查询当天已有的最大订单号
        LambdaQueryWrapper<SupplierContactDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.likeRight(SupplierContactDO::getContractNo, contractNoPrefix + datePart);
        queryWrapper.orderByDesc(SupplierContactDO::getContractNo);
        queryWrapper.last("LIMIT 1");
        SupplierContactDO supplierContact = this.getOne(queryWrapper);

        // 查询当天已有的最大订单号
        LambdaQueryWrapper<PurchaseContractDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.likeRight(PurchaseContractDO::getContractNo, contractNoPrefix + datePart);
        wrapper.orderByDesc(PurchaseContractDO::getContractNo);
        wrapper.last("LIMIT 1");
        PurchaseContractDO existingPurchaseContract = purchaseContractService.getOne(wrapper);

        // 生成序列号
        int maxSequence = 0;
        if (supplierContact != null) {
            String contractNo = supplierContact.getContractNo();
            maxSequence = Integer.parseInt(contractNo.substring((contractNoPrefix + datePart).length()));
        }
        if (existingPurchaseContract != null) {
            String contractNo = existingPurchaseContract.getContractNo();
            int seq = Integer.parseInt(contractNo.substring((contractNoPrefix + datePart).length()));
            maxSequence = Math.max(maxSequence, seq);
        }
        int nextSequence = maxSequence + 1;
        String sequencePart = String.format("%03d", nextSequence);
        return contractNoPrefix + datePart + sequencePart;
    }
}